from flask import render_template, session, current_app, g, abort, request, jsonify

from info import constants, db
from info.models import User, News, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blu

@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    """
    新闻详情页展示
    :param news_id:
    :return:
    """
    user = g.user
    # 右侧新闻排行逻辑
    # 按照点击量排序，查询出前6个
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as a:
        current_app.logger.error(a)
    # 按照查询取出的是news对象，进一步遍历对象，将对象的字典添加至字典列表中
    news_dict_list = [ news.to_basic_dict() for news in news_list]
    # for news in news_list:
    #     news_dict_list.append(news.to_basic_dict())

    # 根据news_id查询新闻内容
    try:
        news = News.query.get(news_id)
    except Exception as a:
        current_app.logger.error(a)
        abort(404)
    if not news:
        abort(404)
    # 更新新闻点击次数
    news.clicks += 1
    # 判断是否关注新闻作者
    is_followed = False
    # 用户是否收藏状态 默认为未收藏
    is_collected = False
    # 判断用户是否收藏过
    if g.user:
         if news in user.collection_news:
             is_collected = True
         if news.user:
             if news.user.followers.filter(User.id == g.user.id).count() > 0:
                 is_followed = True
         # if User.query.get(news.user_id) in user.followed:
         #     is_followed = True
    # 根据news_id查询评论数据
    comments = []
    try:
        comments =Comment.query.filter(Comment.news_id==news_id).order_by(Comment.create_time.desc()).all()
    except Exception as a:
        current_app.logger.error(a)
    comment_likes = []
    if g.user:
        try:
            # 查询当前新闻页所有评论数
            comment_cur_id = [ comment_id.id for comment_id in comments]
            # 当前页当前评论当前用户所有点赞的记录
            comments_like_id = CommentLike.query.filter(CommentLike.comment_id.in_(comment_cur_id),CommentLike.user_id==g.user.id).all()
            # 取出所有记录的id
            comment_likes = [ item.comment_id for item in comments_like_id]
        except Exception as a:
            current_app.logger.error(a)

    comments_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False  # 设置是否点赞值，默认为false
        if comment.id in comment_likes:
            # 若评论id在点赞列表里，则将值改为true
            comment_dict['is_like'] = True
        comments_list.append(comment_dict)

    data = {
        'user': user.to_dict() if user else None,
        'news_dict_list': news_dict_list,
        'news': news.to_dict(),
        'is_collected':is_collected,
        'comments_list':comments_list,
        'is_followed':is_followed
    }
    return render_template("news/detail.html",data=data)


@news_blu.route('/news_collect',methods = ['POST'])
@user_login_data
def news_collect():
    """
    收藏取消收藏功能实现
    :return:
    """
    # 1、获取参数
    param_dict = request.json
    news_id = param_dict.get('news_id')
    action = param_dict.get('action')
    user = g.user
    # 若用户登录，才可以使用收藏功能
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录，不能使用收藏功能')
    # 2、校验参数
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        news_id = int(news_id)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 3、根据news_id获取新闻信息
    try:
        news = News.query.get(news_id)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询错误')
    # 4、判断用户是否收藏该新闻
    if action == 'action':
        # 若用户已收藏
        # 取消收藏
        if news in user.collection_news:
            user.collection_news.remove(news)
    else:
        # 添加收藏
        if news not  in user.collection_news:
            user.collection_news.append(news)
    # 5、返回成功响应
    return jsonify(errno=RET.OK,errmsg='操作成功')


@news_blu.route('/news_comment',methods = ['POST'])
@user_login_data
def news_comment():
    """
    新闻评论功能
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录,不能使用评论功能')
    # 1、获取参数
    params_dict = request.json
    news_id = params_dict.get('news_id',None)
    comment_str = params_dict.get('comment',None)
    parent_id = params_dict.get('parent_id',None)
    # 2、校验参数
    if not all([news_id,comment_str]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 3、根据新闻id查询新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询错误')
    if not news:
        return jsonify(errno=RET.DATAERR,errmsg='新闻数据不存在')
    # 4、将获取的评论内容及新闻id添加至数据库评论表
    # 初始化模型
    comment = Comment()
    comment.news_id = news_id
    comment.user_id = user.id
    comment.content = comment_str
    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as a:
        current_app.logger.error(a)
        db.session.rollback()
    # 返回响应
    return jsonify(errno=RET.OK,errmsg='操作成功',data=comment.to_dict())

@news_blu.route('/comment_like',methods = ['POST'])
@user_login_data
def comment_like():
    """
    用户点赞功能实现
    :return:
    """
    # 判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录,不能使用评论功能')
    # 1、获取参数
    param_dict = request.json
    comment_id = param_dict.get('comment_id',None)
    action = param_dict.get('action',None)
    # 2、校验参数
    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        comment_id = int(comment_id)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if action not in ['add','remove']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 查询评论
    try:
        comment = Comment.query.get(comment_id)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')
    if not comment:
        return jsonify(errno=RET.DATAERR, errmsg='评论不存在')
    # 3、点赞 取消点赞
    if action == 'add':
        # 根据评论id和用户id查询，用户点赞情况
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if not comment_like:
            # 点赞 在数据库表中添加点赞数据
            comment_like_model = CommentLike()
            comment_like_model.comment_id = comment_id
            comment_like_model.user_id = user.id
            db.session.add(comment_like_model)
            comment.like_count += 1  # 点赞数量加1
    else:
        # 取消点赞
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if comment_like:
            db.session.delete(comment_like)
    try:
        db.session.commit()
    except Exception as a:
        current_app.logger.error(a)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库操作失败')
    # 返回响应
    return jsonify(errno=RET.OK, errmsg='操作成功')


@news_blu.route('/followed_user',methods=['POST'])
@user_login_data
def followed_user():
    """用户关注/取消关注新闻作者"""
    user = g.user
    # 获取参数
    user_id = request.json.get('user_id')
    action = request.json.get('action')
    # 校验参数
    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    if action not in ('follow','unfollow'):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        uuser = User.query.get(user_id)
    except Exception as a:
        current_app.logger.error(a)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询错误')
    if not uuser:
        return jsonify(errno=RET.DATAERR,errmsg='用户不存在')
    if action == 'follow':
        if uuser not in user.followed:
            user.followed.append(uuser)
    else:
        if uuser in user.followed:
            user.followed.remove(uuser)
    return jsonify(errno=RET.OK, errmsg="操作成功")










